import { CacheEnum, RouterEnum } from '@/enum';
import storage from '@/hooks/useStorage';
import router from '@/router';
import type { AxiosRequestConfig } from 'axios';
import axios from 'axios';

/**
 * axios个性化配置
 */
export default class CustomAxios {
  private instance;
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);
    this.interceptorsRequest();
    this.interceptorsResponse();
  }

  // 发送请求,
  public request<T>(config: AxiosRequestConfig): Promise<T> {
    return this.instance
      .request<T>(config)
      .then((response) => response)
      .catch((error) => error);
  }

  // 添加请求拦截器
  private interceptorsRequest() {
    this.instance.interceptors.request.use(
      (config) => {
        // 请求头携带token
        config.headers.Authorization = `Bearer ${storage.getItem(CacheEnum.TOKEN_NAME)}`;
        return config;
      },
      (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
      },
    );
  }

  // 添加响应拦截器
  private interceptorsResponse() {
    this.instance.interceptors.response.use(
      (response) => {
        return response;
      },
      (error) => {
        const errorMessage = error.response.data.message;

        switch (error.response.status) {
          // 服务器登录权限过期
          case 401:
            storage.remove(CacheEnum.TOKEN_NAME);
            ElNotification({
              title: '登录过期',
              message: '请重新登录',
              type: 'error',
            });
            router.push({ name: RouterEnum.LOGIN });
            break;
          // 表单验证错误
          case 400:
            ElNotification({
              title: '表单验证错误',
              message: errorMessage,
              type: 'error',
            });
            break;
        }
        return error;
      },
    );
  }
}
